package it.gameplanet.client.widgets.support;

import java.util.Map;

import com.google.gwt.event.dom.client.ContextMenuEvent;
import com.google.gwt.event.dom.client.ContextMenuHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.PopupPanel;

public abstract class AbstractContextMenuHandler implements ContextMenuHandler {

	final private PopupPanel popupPanel = new PopupPanel(true);
	
	public AbstractContextMenuHandler() {
		initMenu(getMenuBar());
	}

	protected abstract Map<String, Command> getMenuBar();
	
	private void initMenu(final Map<String, Command> menu)
	{
		  MenuBar popupMenuBar = new MenuBar(true);
		  
		  for(final String menuName: menu.keySet()) {
			  MenuItem inserisciArticoloMenu = new MenuItem(menuName, new Command() {
				@Override
				public void execute() {
					popupPanel.hide();
					menu.get(menuName).execute();
				}
			  });
			  inserisciArticoloMenu.addStyleName("popup-item");
			  popupMenuBar.addItem(inserisciArticoloMenu);
		  }
		  
		  popupPanel.setStyleName("popup");		 
		  popupPanel.add(popupMenuBar);
		  
		  popupMenuBar.setVisible(true);
	}

	@Override
	public void onContextMenu(ContextMenuEvent event) {
		  int x = event.getNativeEvent().getClientX();
		  int y = event.getNativeEvent().getClientY();
		  popupPanel.setPopupPosition(x, y);
		  popupPanel.show();
	}
	
}
